'use strict';

    angular.module('app')
        .controller('roleUpdateController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster',
                                             function($scope, $rootScope, $state, $timeout, toaster) {
        var title = "";
        if($state.includes('**.role.update')){
            title="编辑角色";
            var id = $state.params.id;
            activate(id);
        }else if($state.includes('**.role.create')){
            title="添加角色";
            $scope.record={'roleType': 1};
            $scope.model=[
	        	{
		        	'id' : 1,
		        	'name' : '业务角色'
	        	},
	        	{
		        	'id' : 2,
		        	'name' : '管理角色'
	        	},
	        	{
		        	'id' : 3,
		        	'name' : '系统内置角色'
	        	}
	        ];
            //validate(null);
            setTimeout(function(){
                !$rootScope.$$phase && $scope.$apply();
            },300);

        }
        $scope.title = $rootScope.title = title;
        $scope.loading = true;
        //初始化验证
        //validate($scope);
        $scope.submit= function(){
            var m = $scope.record;
            if(m){
                $scope.isDisabled = true;//提交disabled
                $.ajax({
    				url : $scope.record.id ? $scope.app.project_name+'/role/update' : $scope.app.project_name+'/role/add',
    				data: $scope.record
    			}).then(callback);
            }
            function callback(result) {
                if(result.httpCode ==200){//成功
                    toaster.clear('*');
                    toaster.pop('success', '', "保存成功");
                    $timeout(function(){
                        $state.go('main.sys.role.list');
                    },2000);
                }else{
                    toaster.clear('*');
                    toaster.pop('error', '', result.msg);
                    $scope.isDisabled = false;
                }
            }
        }

        // 初始化页面
        function activate(id) {
	        $scope.loading = true;
        	$.ajax({
				url : $scope.app.project_name+'/role/read/detail',
				data: {'id': id}
			}).then(function(result) {
		        $scope.loading = false;
		        $scope.model=[
		        	{
			        	'id' : 1,
			        	'name' : '业务角色'
		        	},
		        	{
			        	'id' : 2,
			        	'name' : '管理角色'
		        	},
		        	{
			        	'id' : 3,
			        	'name' : '系统内置角色'
		        	}
		        ];
				if (result.httpCode == 200) {
					$scope.record = result.data;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
        }

    }]);